package com.js.lib.endecrypt;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import com.js.lib.cache.SysCache;

//import com.js.lib.cache.old20220111.SysCache;


/**
 * 
 * @类名: RSAHelper
 * @说明: RSA加解密类
 *		 加密算法: "RSA/ECB/PKCS1Padding", 公钥进行加密; 私钥进行解密.
 *
 * @author: kenny
 * @Date	2017年6月2日下午2:17:09
 * 修改记录：
 *
 * @see
 */
public class RSAHelper {

	public final static String VAR_PUBLIC_KEY="ENC_DEC_KEY:publicKey";
	public final static String VAR_PRIVATE_KEY="ENC_DEC_KEY:privateKey";
	
	private static String publicKey = null;
	private static String privateKey = null;
	
	//生成公钥和私钥
	public static void genPublicPrivateKey() throws NoSuchAlgorithmException, IOException{
		
	    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");   
	    SecureRandom secureRandom = new SecureRandom(new Date().toString().getBytes());  
	    keyPairGenerator.initialize(1024, secureRandom);  
	    KeyPair keyPair = keyPairGenerator.genKeyPair();  
	    //公钥
	    byte[] publicKeyBytes = keyPair.getPublic().getEncoded();  
	    publicKey = Base64Utils.byteToString(publicKeyBytes);

	    //私钥
	    byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
	    privateKey = Base64Utils.byteToString(privateKeyBytes);
	}
	
	//公钥加密
	public static String RsaEncrypt(String src) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, IOException{
        Cipher cipher = Cipher.getInstance("RSA");  
        PublicKey pubKey = (PublicKey) strToPublicKey((String)SysCache.getInstance().get(VAR_PUBLIC_KEY));
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);  
        byte[] bodyByte = cipher.doFinal(src.getBytes());
        String cipherText = Base64Utils.byteToString(bodyByte);
        //加密后的东西  
		return cipherText;
	}
	public static String encrypt(String src){
		try{
			return RsaEncrypt(src);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	
	//私钥解密
	public static String RsaDecrypt(String src) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, InvalidKeyException{
		Cipher cipher = Cipher.getInstance("RSA");
	    //RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey1((String)SysSource.getInstance().getAttribute(Constant.VAR_PRIVATE_KEY));  
		PrivateKey prvKey = (PrivateKey) strToPrivateKey((String)SysCache.getInstance().get(VAR_PRIVATE_KEY));

        byte[] bodyByte = Base64Utils.stringToByte(src);
        cipher.init(Cipher.DECRYPT_MODE, prvKey);
        byte[] plainText = cipher.doFinal(bodyByte); 
        String result = new String(plainText);
        //System.out.println("解密后 : " + new String(result));
        return result;

	}
	
	public static String decrypt(String src){
		try{
			return RsaDecrypt(src);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	public static void testEnDe(){
		try{
			Date newDate = new Date();
	        String input = newDate.toString(); 
	        System.out.println("未加密: " + new String(input));
	        
			//GenPublicKey();
	        publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClL9urKZAz35nbo/5mr4Ic408L9lcz+veZxVHGVoDRVTDpxiYNXwq3jcB1htvG+XkSwqaxylB8C5E2cNJzGxQGSyea9Ecv3453hyRWU9gTGdpk71p1hxmremro8AqkVnqCCs0SmoXVBapTjos48EUqBVG59WvhGNg0FwsC1KLBUQIDAQAB";
	        privateKey="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKUv26spkDPfmduj/mavghzjTwv2"
	        		+ "VzP695nFUcZWgNFVMOnGJg1fCreNwHWG28b5eRLCprHKUHwLkTZw0nMbFAZLJ5r0Ry/fjneHJFZT"
	        		+ "2BMZ2mTvWnWHGat6aujwCqRWeoIKzRKahdUFqlOOizjwRSoFUbn1a+EY2DQXCwLUosFRAgMBAAEC"
	        		+ "gYAU8q/B0gCGg4mob/CYJxOyBCWHF9NRNTdnGb3YECo/4bTVQJqcwXvDcUeB3/tJDWQMPAEVtNlm"
	        		+ "EbV1mPMnQ7zTJtbK8IAnUeq5yXz0W6o7lxfsiq2fMmPXV4MBviNmzc5Y+KEO9O3fkQ0GnV/sWbCN"
	        		+ "5GYUoXFIWGSt/VLCyGeDfQJBAOwgonMsDfW4kAzD4wbEsAXUFLU6uNPBvDZUk0SHCa1VaxMH4jbe"
	        		+ "cZgA0rA1tMyQST4cf3OZdCJTgq0MHpXdpecCQQCzFs9ftpFS9phHMN19O5OVCmvegxwoRNCDn0Zj"
	        		+ "L2wsW+zUp4n2phw3F7HFRmaM1q5q3NrpIutTM9MUxc+p/AgHAkEA02AHbEhUmtHECdlVItrxo9YN"
	        		+ "T4qop883F/+v8Vlc/VCI0HlvNKT+VQ7vjBQXrEPBfRtvsGD/SDcvtI8z1f6bowJAJblfU20UraIu"
	        		+ "L4jWjyO2kcWRNVzu2HiuZ5tsa0Y5BhsTBzSHdkJFXUGLe9+5iF9MfEwrfMKTSYJ4Kz8D4G2rjwJB"
	        		+ "AKln8ty+FhOWwbCGFE8MMkhcu/fRf6GB2btyMhf+SOcHKLZ+rt+eEP9TNFsjooveTaoThd0TQfXY"
	        		+ "MZaCFzMbSkU=";
			Cipher cipher = Cipher.getInstance("RSA");
			
	        PublicKey pubKey = strToPublicKey(publicKey); 
	        cipher.init(Cipher.ENCRYPT_MODE, pubKey);  
	        byte[] bodyByte = cipher.doFinal(input.getBytes());
	        String cipherText = Base64Utils.byteToString(bodyByte);
	        //加密后的东西  
	        System.out.println("加密后: " + new String(cipherText)); 
	        
	        
			
	        PrivateKey prvKey = strToPrivateKey(privateKey);  
	        byte[] bodyByte1 = Base64Utils.stringToByte(cipherText);
	        cipher.init(Cipher.DECRYPT_MODE, prvKey);
	        byte[] plainText = cipher.doFinal(bodyByte1); 
	        String result = new String(plainText);
	        System.out.println("解密后 : " + new String(result));

			
		}catch(Exception e){
			System.out.println("***  " + e);
		}
	}	

	//把字符串公钥转换成byte公钥
	private static PublicKey strToPublicKey(String val) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException{
		byte[] keyBytes = Base64Utils.stringToByte(val);
		
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);  
        KeyFactory kf = KeyFactory.getInstance("RSA");   
        return kf.generatePublic(spec);  		
	}
	//把字符串私钥转换成byte私钥
	private static PrivateKey strToPrivateKey(String val) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException{
		byte[] keyBytes = Base64Utils.stringToByte(val);
        PKCS8EncodedKeySpec spec =new PKCS8EncodedKeySpec(keyBytes);  
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);  
		
	}

	public static String getPublicKey() {
		if (publicKey == null){
			try {
				genPublicPrivateKey();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return publicKey;
	}


	public static String getPrivateKey() {
		if (privateKey == null){
			try {
				genPublicPrivateKey();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return privateKey;
	}

	

}
